package com.littlec.sdk.manager;

import java.io.File;
import org.jivesoftware.smack.AbstractConnectionListener;
import org.jivesoftware.smack.ReconnectionManager;
import org.jivesoftware.smack.XMPPConnection;

import com.littlec.sdk.XMPPConnectionManager;
import com.littlec.sdk.business.Login;
import com.littlec.sdk.entity.CMContact;
import com.littlec.sdk.entity.EnumLoginStatus;
import com.littlec.sdk.utils.CMChatGlobalStorage;
import com.littlec.sdk.utils.CMChatListener;
import com.littlec.sdk.utils.CommonUtils;
import com.littlec.sdk.utils.MyLogger;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

public class CMAccountManager {
	public static final MyLogger sLogger = MyLogger
			.getLogger("CMAccountManager");
	private static CMAccountManager mCMAccountManagerInstance = null;
	private static Context mAppContext = null;
	private CMContact mCurrentAccount = null;
	private AbstractConnectionListener mConnectionListener = null;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			CMChatListener.OnConnectionListener mListener = (CMChatListener.OnConnectionListener) msg.obj;
			if (mListener == null)
				return;
			switch (msg.what) {
			case 100:
				mListener.onDisConnected();
				break;
			case 101:
				CMMessageManager.getInstance().stopResendMessage();
				mListener.onAccountDestroyed();
				break;
			case 103:
				mListener.onReConnected();
				break;
			case 102:
				CMMessageManager.getInstance().stopResendMessage();
				mListener.onAccountConflict();
				break;
			}
		}
	};

	protected static CMAccountManager getInstance() {
		if (mCMAccountManagerInstance == null) {
			synchronized (CMAccountManager.class) {
				if (mCMAccountManagerInstance == null) {
					mCMAccountManagerInstance = new CMAccountManager();
				}
			}
		}
		return mCMAccountManagerInstance;
	}

	public void init(Context appContext, String appkey) {
		sLogger.e("==do init");
		if (appContext == null) {
			throw new NullPointerException("传入Context不能为空");
		}
//		if (appkey == null) {
//			throw new NullPointerException("app key �������,Ӧ��Ϊ6λ���ֺ��2λ��ĸ");
//		}
		appkey = "";
		// if (!SdkUtils.checkAppKey(appkey)) {
		// throw new RuntimeException("app key �������,Ӧ��Ϊ6λ���ֺ��2λ��ĸ");
		// }
		mAppContext = appContext;
		com.littlec.sdk.CMChatConfig.appKey = appkey.trim().toLowerCase();
		pathConfig();
	}

	public void addConnectionListener(
			final CMChatListener.OnConnectionListener listener) {
		if (listener == null)
			return;
		XMPPConnection conn = XMPPConnectionManager.getInstance()
				.getConnection();
		if (conn == null) {
			throw new NullPointerException("请在登录成功后，再调用连接状态的监听");
		}
		this.mConnectionListener = new CMAbstractConnectionListener(listener) {

			public void reconnectionSuccessful() {
				// //�˺���������Ͽ����Ӻ��Զ������ɹ�
				CMAccountManager.sLogger.e("reconnectionSuccessful");
				CMChatGlobalStorage.getInstance().setLoginStatus(
						EnumLoginStatus.STATE_LOGINED);
				Message msg = CMAccountManager.this.mHandler.obtainMessage(103,
						listener);
				msg.sendToTarget();
			}

			public void connectionClosedOnError(Exception e) {
				CMAccountManager.sLogger.e("connectionClosedOnError");

				boolean conflict = false;
				boolean destroyed = false;
				if (e.getMessage() != null) {
					conflict = e.getMessage().equals("stream:error (conflict)");
					destroyed = e.getMessage().equals(
							"stream:error (not-authorized)");
				}
				if (conflict) {
					CMAccountManager.sLogger.e("======�˺�conflict=======");

					Message msg = CMAccountManager.this.mHandler.obtainMessage(
							102, listener);
					msg.sendToTarget();
				} else if (destroyed) {
					CMAccountManager.sLogger.e("======�˺� destroyed =======");

					Message msg = CMAccountManager.this.mHandler.obtainMessage(
							101, listener);
					msg.sendToTarget();
				} else {
					CMChatGlobalStorage.getInstance().setLoginStatus(
							EnumLoginStatus.STATE_STANDBY);
					Message msg = CMAccountManager.this.mHandler.obtainMessage(
							100, listener);
					msg.sendToTarget();
				}
			}

			public void connectionClosed() {

			}
		};
		conn.addConnectionListener(this.mConnectionListener);
	}

	private void pathConfig() {
		String rootDir = CommonUtils.getDataDir(mAppContext);
		CMChatGlobalStorage.MTC_DATA_PATH = rootDir + "/xmpp";
		CMChatGlobalStorage.MTC_DATA_EMAIL_PATH = CMChatGlobalStorage.MTC_DATA_PATH
				+ "/email";
		CMChatGlobalStorage.MTC_PROFILE_PATH = CMChatGlobalStorage.MTC_DATA_PATH
				+ "/profiles";
		CMChatGlobalStorage.MTC_LOG_PATH = CMChatGlobalStorage.MTC_DATA_PATH
				+ "/log";
		CMChatGlobalStorage.MTC_CRASH_LOG_PATH = CMChatGlobalStorage.MTC_DATA_PATH
				+ "/crash_log";
		CMChatGlobalStorage.MTC_DOWNLOAD_PATH = CMChatGlobalStorage.MTC_DATA_PATH
				+ "/download";
		CMChatGlobalStorage.MTC_DOWNLOAD_APP_UPDATE_PATH = CMChatGlobalStorage.MTC_DOWNLOAD_PATH
				+ "/appupdate";

		File file = new File(CMChatGlobalStorage.MTC_DATA_PATH);
		file.mkdirs();
		file = new File(CMChatGlobalStorage.MTC_DATA_EMAIL_PATH);
		file.mkdirs();
		file = new File(CMChatGlobalStorage.MTC_LOG_PATH);
		file.mkdirs();
		file = new File(CMChatGlobalStorage.MTC_CRASH_LOG_PATH);
		file.mkdirs();
		file = new File(CMChatGlobalStorage.MTC_DOWNLOAD_PATH);
		file.mkdirs();
		file = new File(CMChatGlobalStorage.MTC_DOWNLOAD_APP_UPDATE_PATH);
		file.mkdirs();

		file = new File(rootDir + "/PicPool");
		if (file != null) {
			CommonUtils.delete(file);
		}
		file = new File(CMChatGlobalStorage.MTC_PROFILE_PATH);
		file.mkdirs();
	}

	public void doLogin(String userName, String passWord,
			CMChatListener.OnCMListener loginListener) {
//		userName = "15025443417";
		passWord = "123456";
		CMChatGlobalStorage.getInstance().setmLoginUserName(userName);
		if ((userName == null) || (passWord == null) || (loginListener == null)) {
			throw new NullPointerException();
		}
		Login.getInstance().doLogin(userName, passWord, loginListener);
	}

	public void doLogOut() {
		CMChatGlobalStorage.getInstance().setLoginStatus(
				EnumLoginStatus.STATE_NONE);
		CMMessageManager.getInstance().release();
		XMPPConnection conn = XMPPConnectionManager.getInstance()
				.getConnection();
		if (conn == null)
			return;
		XMPPConnectionManager.getInstance().disconnect();

		Login.getInstance().destory();
		CMChatGlobalStorage.getInstance().destory();
		CMContactManager.getInstance().destory();
		mCMAccountManagerInstance = null;
	}

	public Context getApplicationContext() {
		return mAppContext;
	}

	public CMContact getCurrentAccount() {
		if (this.mCurrentAccount == null) {
			this.mCurrentAccount = CMIMHelper.getCmContactManager()
					.getLoginedUserInfo();
		}
		return this.mCurrentAccount;
	}
}
